/**
* 基础菜单 产品管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="code" label="ProductKey" width="200">
      </el-table-column>
      <el-table-column sortable prop="name" label="产品名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="cateName" label="品类" width="100">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="添加时间" width="150">
        <template slot-scope="scope">
          <div>{{scope.row.createAt|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" @click="handleEditThingModel(scope.$index, scope.row)">物模型</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="ProductKey" prop="code">
          <el-input size="small" v-model="editForm.code" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeType">
          <el-radio-group v-model="editForm.nodeType">
            <el-radio :label="0">网关设备</el-radio>
            <el-radio :label="1">网关子设备</el-radio>
            <el-radio :label="2">直连设备</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="品类" prop="category">
          <el-select size="small" v-model="editForm.category" placeholder="请选择品类">
            <el-option v-for="cate in categories" :label="cate.name" :value="cate.id" :key="cate.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品图片" prop="pic">
          <div class="pic-upload">
            <img v-if="editForm.img && !showUpload" :src="editForm.img" class="avatar">
            <el-upload v-if="showUpload" class="upload-demo" drag :action="getUploadAction()" :headers="getAuthHeaders()"
              :on-success="uploadSuccess" multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <el-button v-if="!showUpload" size="mini" @click="onShowUpload">上传</el-button>
            <el-button v-if="showUpload" size="mini" @click="onHideUpload">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitEditForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑物模型 -->
    <el-dialog title="产品物模型" :visible.sync="editThingModelFormVisible" width="70%" @click="closeDialog" class="thing-model-dlg"
      top="2vh">
      <ThingModel :productKey="currentProductKey"></ThingModel>
    </el-dialog>

  </div>
</template>

<script>
  import {
    CategoryList,
    ProductList,
    ProductSave,
    ThingModelSave
  } from '../../api/productApi'
  import Pagination from '../../components/Pagination'
  import ThingModel from './ThingModel.vue'
  export default {
    data() {
      return {
        nshow: true, //switch开启
        fshow: false, //switch关闭
        loading: false, //是显示加载
        editFormVisible: false,
        editThingModelFormVisible: false, //控制编辑页面显示与隐藏
        title: '添加',
        editForm: {
          code: '',
          name: '',
          category: '',
          nodeType: 0
        },
        thingModelForm: {},
        currentProductKey: '',
        categories: [],
        // rules表单验证
        rules: {},
        showUpload: false,
        formInline: {
          page: 1,
          limit: 10,
          varLable: '',
          varName: '',
          token: localStorage.getItem('logintoken')
        },
        // 删除部门
        seletedata: {
          ids: '',
          token: localStorage.getItem('logintoken')
        },
        userparm: [], //搜索权限
        listData: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        }
      }
    },
    // 注册组件
    components: {
      Pagination,
      ThingModel
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
      this.getdata(this.formInline)
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      getdata(parameter) {
        this.loading = true
        CategoryList(parameter).then((res => {
          this.categories = res;
          let cateMap = {};
          this.categories.forEach(c => {
            cateMap[c.id] = c.name;
          });

          ProductList(parameter)
            .then(res => {
              this.loading = false
              res.data.forEach((p => {
                p.cateName = cateMap[p.category];
              }))

              this.listData = res.data
              // 分页赋值
              this.pageparm.currentPage = this.formInline.page
              this.pageparm.pageSize = this.formInline.limit
              this.pageparm.total = res.count

            }, () => {
              this.loading = false
            })
        }))
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata(this.formInline)
      },
      // 搜索事件
      search() {
        this.getdata(this.formInline)
      },
      randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
          pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      },
      onShowUpload() {
        this.showUpload = true
      },
      onHideUpload() {
        this.showUpload = false
      },
      getUploadAction() {
        return window.apiBaseUrl + "/product/uploadImg/" + this.editForm.code
      },
      getAuthHeaders() {
        return {
          'Authorization': 'Basic ' + localStorage.getItem('logintoken')
        }
      },
      uploadSuccess(response) {
        this.editForm.img = response
        this.showUpload = false
      },
      handleEdit(index, row) {
        this.editFormVisible = true
        if (row != undefined && row != 'undefined') {
          this.showUpload = false
          this.title = '编辑产品'
          this.editForm.code = row.code
          this.editForm.name = row.name
          this.editForm.category = row.category
          this.editForm.nodeType = row.nodeType
          this.editForm.img = row.img
        } else {
          this.title = '添加产品'
          this.editForm.code = this.randomString(16)
          this.editForm.name = ''
          this.editForm.category = ''
          this.editForm.nodeType = 0
        }
      },
      //显示编辑界面
      handleEditThingModel(index, row) {
        this.editThingModelFormVisible = true
        let that = this;
        setTimeout(function() {
          that.currentProductKey = "";
        }, 100)
        setTimeout(function() {
          that.currentProductKey = row.code;
        }, 110)
      },
      submitEditForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            ProductSave(this.editForm).then(() => {
              this.editFormVisible = false
              this.loading = false
              this.$message({
                type: 'success',
                message: '保存成功！'
              })
              this.search()
            }, () => {
              this.editFormVisible = false
              this.loading = false
            })
          }
        })
      },
      // 保存物模型
      submitThingModelForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            ThingModelSave({
                productKey: this.thingModelForm.productKey,
                model: JSON.stringify(this.thingModelForm.model)
              })
              .then(() => {
                this.editThingModelFormVisible = false
                this.loading = false
                this.$message({
                  type: 'success',
                  message: '保存成功！'
                })
              }, () => {
                this.editThingModelFormVisible = false
                this.loading = false
              })
          } else {
            return false
          }
        })
      },
      // 关闭编辑、增加弹出框
      closeDialog() {
        this.editThingModelFormVisible = false
        this.editFormVisible = false
      }
    }
  }
</script>

<style>
  .jsoneditor-vue {
    height: 500px !important;
  }

  .thing-model-dlg .el-dialog__body {
    padding: 0 0;

  }
</style>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .pic-upload {}

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 70%;
  }
</style>
